package com.yang.util;

import java.util.Date;
import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

public class JwtUtil {
	
	private static final Logger log = LoggerFactory.getLogger(JwtUtil.class);
	
	/**
	 * token签名
	 * @param id
	 * @param username
	 * @return
	 */
    public static String sign(int id, String username) {
        try {
			Date date = new Date(System.currentTimeMillis() + Constants.EXPIRE_TIME);
			
			Algorithm algorithm = Algorithm.HMAC256(Constants.TOKEN_SECRET);
			
			HashMap<String, Object> header = new HashMap<>(2);
			header.put("typ", "JWT");
			header.put("alg", "HS256");
			
			return JWT.create()
					.withHeader(header)
					.withClaim("username", username)
					.withClaim("id", id)
					.withExpiresAt(date)
					.sign(algorithm);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return null;
		}
    }
    
    /**
     * 验证token
     * @param token
     * @return
     */
    public static boolean verify(String token) {
    	try {
			Algorithm algorithm = Algorithm.HMAC256(Constants.TOKEN_SECRET);
			JWTVerifier verifier = JWT.require(algorithm).build();
			verifier.verify(token);
			return true;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return false;
		}
    }
    
    /**
     * 获取用户名
     * @param token
     * @return
     */
    public static String getUsername(String token) {
    	try {
			DecodedJWT jwt = JWT.decode(token);
			String username = jwt.getClaim("username").asString();
			return username;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return null;
		}
    }
    
    /**
     * 获取登录用户id
     * @param token
     * @return
     */
    public static Integer getUserInfoId(String token) {
    	try {
			DecodedJWT jwt = JWT.decode(token);
			Integer id = jwt.getClaim("id").asInt();
			return id;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return null;
		}
    }

}
